package com.zshan.clinic.mini.service;

import com.zshan.clinic.admin.constant.Constants;
import com.zshan.clinic.admin.service.config.ClinicConfigService;
import com.zshan.clinic.admin.service.customer.CmUserService;
import com.zshan.clinic.common.constant.CommonConstant;
import com.zshan.clinic.common.exception.BusinessFailException;
import com.zshan.clinic.common.util.redis.RedisUtil;
import com.zshan.clinic.common.util.string.StringUtil;
import com.zshan.clinic.common.util.token.JWTHS256;
import com.zshan.clinic.common.util.uuid.IdBuilder;
import com.zshan.clinic.database.model.ClinicConfig;
import com.zshan.clinic.database.model.CmUser;
import com.zshan.clinic.mini.constant.MiniRedisKeyPrefix;
import com.zshan.clinic.mini.entity.SessionKey;
import com.zshan.clinic.mini.entity.UserInfo;
import com.zshan.clinic.mini.entity.WechatLoginRequest;
import com.zshan.clinic.mini.util.WeixinUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author lichen
 */
@Slf4j
@Service
public class LoginService {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private CmUserService cmUserService;

    @Autowired
    private ClinicConfigService clinicConfigService;

    /**
     * 微信小程序登录
     * @param loginRequest
     * @return
     */
    public UserInfo loginByWechat(WechatLoginRequest loginRequest,Long clinicId) {
        log.info("微信登录获取请求参数:{},clinicId:{}",loginRequest,clinicId);
        String code = loginRequest.getCode();
        if(StringUtil.isBlank(code)){
            throw new BusinessFailException("授权CODE不能为空");
        }
        ClinicConfig clinicConfig = clinicConfigService.getClinicConfigById(clinicId);
        if(clinicConfig == null){
            log.info(">>>>>>>>>>>>>>>>>>>没有给诊所配置微信appId>>>>>>>>>>>>>>>>>>>");
            throw new BusinessFailException("登录失败，请稍后重试");
        }
        SessionKey sessionKey = WeixinUtil.getSessionKey(clinicConfig.getWxMiniAppid(),clinicConfig.getWxMiniSecret(),code);
        String openid = sessionKey.getOpenid();
        String unionid = sessionKey.getUnionid();
        //根据openid查询C端用户，如果没有则需要初始化
        CmUser cmUser = cmUserService.getCmUserByOpenid(clinicId,openid);
        if(cmUser == null){
            cmUser = addCmUser(openid,unionid,clinicId);
        }
        //3.登录成功生成token
        String token = JWTHS256.buildJWT(StringUtil.valueOf(cmUser.getCmUserId()));
        UserInfo userInfo = new UserInfo(cmUser.getCmUserId(),cmUser.getNickName(),token,cmUser.getClinicId());
        redisUtil.set(String.format(MiniRedisKeyPrefix.USER_TOKEN,token), userInfo, CommonConstant.MONTH_2);
        return userInfo;
    }

    /**
     * 添加用户
     * @param openid
     * @param unionid
     * @param clinicId
     * @return
     */
    public CmUser addCmUser(String openid,String unionid,Long clinicId) {
        CmUser cmUser = new CmUser();
        cmUser.setNickName(String.format(Constants.CM_NICK_NAME, IdBuilder.getFixedLengthNumber(CommonConstant.DEFAULT_6)));
        cmUser.setAvatarUrl(Constants.CM_DEFAULT_AVATAR);
        cmUser.setOpenid(openid);
        cmUser.setUnionid(unionid);
        cmUser.setClinicId(clinicId);
        return cmUserService.addCmUser(cmUser);
    }

    /**
     * 退出登录
     * @param token
     */
    public void logout(String token) {
        if(StringUtil.isNotBlank(token)){
            //删除redis缓存
            redisUtil.del(String.format(MiniRedisKeyPrefix.USER_TOKEN,token));
        }
    }
}
